<template>
  <div class="setup-dict-container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form inline :model="searchData">
        <el-form-item label="字典名称">
          <el-input
            v-model="searchData.dictName"
            placeholder="请输入字典名称"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAddDict">新增字典</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 左右分栏布局 -->
    <div class="dict-layout">
      <!-- 左侧父节点表格 -->
      <div class="parent-dict-panel">
        <div class="panel-title">父级字典</div>
        <div class="parent-dict-table-wrapper">
          <!-- 表格内容区域 -->
          <div class="parent-dict-table">
            <art-table
              :data="parentDictData"
              :loading="parentLoading"
              :pagination="false"
              highlight-current-row
              show-header-background
              @row-click="handleParentRowClick"
            >
              <el-table-column prop="dictName" label="字典名称" min-width="150" />
              <el-table-column prop="dictDescribe" label="字典描述" min-width="200" />
              <el-table-column prop="createTime" label="创建时间" min-width="180" />
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="scope">
                  <div class="table-actions">
                    <button-table type="edit" @click="handleEditDict(scope.row)" />
                    <el-popconfirm
                      title="确认删除此角色吗？"
                      @confirm="handleDeleteDict(scope.row.dictId)"
                    >
                      <template #reference>
                        <button-table type="delete" @click.stop="() => {}" />
                      </template>
                    </el-popconfirm>
                  </div>
                </template>
              </el-table-column>
            </art-table>
          </div>
          <!-- 分离的分页组件 -->
          <div class="parent-pagination-wrapper">
            <el-pagination
              v-model:current-page="searchData.page"
              v-model:page-size="searchData.pageSize"
              :page-sizes="[5, 10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="parentTotal"
              @size-change="handleParentSizeChange"
              @current-change="handleParentCurrentChange"
            />
          </div>
        </div>
      </div>

      <!-- 右侧子节点表格 -->
      <div class="child-dict-panel">
        <div class="panel-title">
          子级字典
          <el-button
            type="primary"
            size="small"
            v-if="currentParentKey !== null"
            @click="handleAddChildDict"
          >
            新增子级
          </el-button>
        </div>
        <div class="child-dict-table-wrapper">
          <!-- 表格内容区域 -->
          <div class="child-dict-table">
            <art-table
              :data="childTableData"
              :loading="childLoading"
              :pagination="false"
              highlight-current-row
              show-header-background
            >
              <el-table-column prop="dictName" label="字典名称" min-width="150" />
              <el-table-column prop="dictDescribe" label="字典描述" min-width="200" />
              <el-table-column prop="createTime" label="创建时间" min-width="180" />
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="scope">
                  <div class="table-actions">
                    <button-table type="edit" @click="handleEditDict(scope.row)" />
                    <el-popconfirm
                      title="确认删除此角色吗？"
                      @confirm="handleDeleteDict(scope.row.dictId)"
                    >
                      <template #reference>
                        <button-table type="delete" @click.stop="() => {}" />
                      </template>
                    </el-popconfirm>
                  </div>
                </template>
              </el-table-column>
            </art-table>
          </div>
          <!-- 分离的分页组件 -->
          <div class="child-pagination-wrapper">
            <el-pagination
              v-model:current-page="childSearchData.page"
              v-model:page-size="childSearchData.pageSize"
              :page-sizes="[5, 10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="childTotal"
              @size-change="handleChildSizeChange"
              @current-change="handleChildCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 新增/编辑字典对话框 -->
    <el-dialog
      v-model="dictDialogVisible"
      :title="isEdit ? '编辑字典' : '新增字典'"
      width="30%"
      center
      :close-on-click-modal="false"
      @closed="onDictDialogClosed"
    >
      <el-form ref="dictFormRef" :model="dictForm" label-width="80px" :rules="dictFormRules">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="dictForm.dictName" placeholder="请输入字典名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="字典描述" prop="dictDescribe">
          <el-input
            v-model="dictForm.dictDescribe"
            placeholder="请输入字典描述"
            maxlength="200"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item v-if="isAddingChild" label="父级字典">
          <el-input v-model="parentDictName" placeholder="父级字典" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dictDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleDictSubmit"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance } from 'element-plus'

  import { SetupService } from '@/api/setupApi'
  import type { DictType } from '@/api/model/setupModel'
  import { ApiStatus } from '@/utils/http/status'

  // 类型转换辅助函数：安全地将值转换为数字
  const safelyConvertToNumber = (value: number | string | null | undefined): number | null => {
    if (value === null || value === undefined || value === '') {
      return null
    }
    if (typeof value === 'number') {
      return isFinite(value) ? value : null
    }
    const num = parseInt(value, 10)
    return isNaN(num) ? null : num
  }

  // 安全地获取子字典数据
  const safelyGetChildDicts = (dictId: number | null | undefined): void => {
    if (dictId !== null && dictId !== undefined) {
      getChildDicts(dictId)
    }
  }

  // 搜索数据
  const searchData = reactive({
    dictName: '',
    page: 1,
    pageSize: 10
  })

  // 父级字典数据
  const parentDictData = ref<DictType[]>([])
  const parentTotal = ref(0)
  const parentLoading = ref(false)
  // 当前选中的父级字典ID，支持数字类型
  const currentParentKey = ref<number | null>(null)
  const parentDictName = ref('')

  // 子级字典数据
  const childTableData = ref<DictType[]>([])
  const childTotal = ref(0)
  const childLoading = ref(false)
  const childSearchData = reactive({
    page: 1,
    pageSize: 10
  })

  // 字典表单数据
  const dictFormRef = ref<FormInstance | null>()
  const dictDialogVisible = ref(false)
  const isEdit = ref(false)
  const isAddingChild = ref(false)
  const submitLoading = ref(false)

  // 字典表单
  const dictForm = reactive({
    dictId: '',
    dictName: '',
    dictDescribe: '',
    dictPid: ''
  })

  // 字典表单验证规则
  const dictFormRules = {
    dictName: [
      { required: true, message: '请输入字典名称', trigger: 'blur' },
      { min: 2, max: 50, message: '字典名称长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    dictDescribe: [{ max: 200, message: '字典描述不能超过 200 个字符', trigger: 'blur' }]
  }

  // 初始化数据
  onMounted(async () => {
    await getParentDicts()
    // 默认选中第一个父级字典，使新增子级按钮可见
    if (parentDictData.value && parentDictData.value.length > 0) {
      handleParentRowClick(parentDictData.value[0])
    }
  })

  // 获取父级字典列表
  const getParentDicts = async () => {
    parentLoading.value = true
    try {
      console.log('开始请求dictGetAll，参数:', {
        dictName: searchData.dictName,
        page: searchData.page,
        pageSize: searchData.pageSize
      })
      const res = await SetupService.dictGetAll({
        dictName: searchData.dictName,
        page: searchData.page,
        pageSize: searchData.pageSize
      })
      console.log('dictGetAll接口返回:', res)

      // 检查返回数据结构是否符合BaseResult格式
      if (res && typeof res === 'object') {
        console.log('ApiStatus.success:', ApiStatus.success, '类型:', typeof ApiStatus.success)
        console.log('res.code:', res.code, '类型:', typeof res.code)

        // 更健壮地比较状态码，转换为相同类型后比较
        const isSuccess = String(res.code) === String(ApiStatus.success)
        console.log('状态码比较结果:', isSuccess)

        if (isSuccess) {
          // 只显示顶级节点
          // 显示dictPid为空、0、null、undefined的顶级节点
          // 修复类型问题：正确处理PageResult类型的数据
          let rawData: DictType[] = []
          let total = 0

          console.log('res.data:', res.data)

          // 兼容多种返回数据结构
          if (Array.isArray(res.data)) {
            // 如果res.data直接是数组
            rawData = res.data
            total = rawData.length
          } else if (res.data && typeof res.data === 'object') {
            if ('list' in res.data && Array.isArray(res.data.list)) {
              // 如果res.data是分页结构，包含list字段
              rawData = res.data.list
              total = res.data.total || 0
            } else {
              // 其他情况，尝试将res.data作为单条记录处理
              rawData = [res.data]
              total = 1
            }
          }

          parentDictData.value = rawData.filter((item) => !item.dictPid || item.dictPid === 0)
          // 使用接口返回的total作为总数，而不是过滤后的数组长度
          parentTotal.value = total
          console.log('处理后的数据:', parentDictData.value)
        } else {
          // 更详细地检查res对象的结构
          console.error('接口返回错误状态:', res)
          console.error('错误码:', res.code)
          console.error('错误消息:', res.message)

          // 处理可能的undefined或null值
          const errorCode = res.code !== undefined ? res.code : '未知'
          const errorMessage = res.message || '获取父级字典列表失败'

          ElMessage.error(`${errorMessage} (错误码: ${errorCode})`)
          parentDictData.value = []
          parentTotal.value = 0
        }
      } else {
        console.error('接口返回格式错误，不是有效的对象:', res)
        ElMessage.error('获取父级字典列表失败：返回格式错误')
        parentDictData.value = []
        parentTotal.value = 0
      }
    } catch (error) {
      ElMessage.error('获取父级字典列表失败')
      console.error(error)
      parentDictData.value = []
      parentTotal.value = 0
    } finally {
      parentLoading.value = false
    }
  }

  // 处理父级字典分页大小变化
  const handleParentSizeChange = (size: number) => {
    searchData.pageSize = size
    getParentDicts()
  }

  // 处理父级字典当前页变化
  const handleParentCurrentChange = (current: number) => {
    searchData.page = current
    getParentDicts()
  }

  // 获取子级字典列表
  const getChildDicts = async (dictPid: number) => {
    childLoading.value = true
    try {
      const res = await SetupService.dictGetChilds({
        dictPid: dictPid,
        page: childSearchData.page,
        pageSize: childSearchData.pageSize
      })
      if (res.code === ApiStatus.success) {
        // 修复类型问题：根据实际返回的数据结构调整
        let rawData: DictType[] = []
        let total = 0

        // 使用类型守卫检查res.data的结构
        if (Array.isArray(res.data)) {
          // 如果res.data直接是数组
          rawData = res.data
          total = rawData.length
        } else if (res.data && typeof res.data === 'object' && 'list' in res.data) {
          // 如果res.data包含list字段（分页结构）
          const pageData = res.data as { list: DictType[]; total?: number }
          rawData = pageData.list || []
          total = pageData.total || rawData.length
        }

        childTableData.value = rawData
        childTotal.value = total
      } else {
        ElMessage.error(res.message || '获取子级字典列表失败')
        childTableData.value = []
        childTotal.value = 0
      }
    } catch (error) {
      ElMessage.error('获取子级字典列表失败')
      console.error(error)
      childTableData.value = []
      childTotal.value = 0
    } finally {
      childLoading.value = false
    }
  }

  // 点击父级字典行
  const handleParentRowClick = (row: DictType) => {
    // 安全处理dictId，确保类型正确
    currentParentKey.value = row.dictId || null
    parentDictName.value = row.dictName || ''
    childSearchData.page = 1
    safelyGetChildDicts(currentParentKey.value)
  }

  // 处理子级字典分页大小变化
  const handleChildSizeChange = (size: number) => {
    childSearchData.pageSize = size
    safelyGetChildDicts(currentParentKey.value)
  }

  // 处理子级字典当前页变化
  const handleChildCurrentChange = (current: number) => {
    childSearchData.page = current
    safelyGetChildDicts(currentParentKey.value)
  }

  // 新增字典（父级）
  const handleAddDict = () => {
    isEdit.value = false
    isAddingChild.value = false
    // 重置表单
    Object.assign(dictForm, {
      dictId: '',
      dictName: '',
      dictDescribe: '',
      dictPid: '' // 父级字典设置dictPid为空字符串
    })
    // 清空表单验证
    if (dictFormRef.value) {
      dictFormRef.value.clearValidate()
    }
    dictDialogVisible.value = true
  }

  // 新增子级字典
  const handleAddChildDict = () => {
    if (currentParentKey.value === null) return
    isEdit.value = false
    isAddingChild.value = true
    // 重置表单，安全设置dictPid类型
    const dictPid = safelyConvertToNumber(currentParentKey.value)
    Object.assign(dictForm, {
      dictId: '',
      dictName: '',
      dictDescribe: '',
      dictPid: dictPid !== null ? dictPid : 0
    })
    // 清空表单验证
    if (dictFormRef.value) {
      dictFormRef.value.clearValidate()
    }
    dictDialogVisible.value = true
  }

  // 处理搜索
  const handleSearch = () => {
    searchData.page = 1
    getParentDicts()
  }

  // 处理重置
  const handleReset = () => {
    searchData.dictName = ''
    searchData.page = 1
    searchData.pageSize = 10
    getParentDicts()
  }

  // 编辑字典
  const handleEditDict = async (row: DictType) => {
    // 确保dictId存在且为有效值
    if (row.dictId === undefined || row.dictId === null) {
      ElMessage.error('无效的字典ID')
      return
    }

    isEdit.value = true
    isAddingChild.value = !!row.dictPid && row.dictPid !== 0
    // 清空表单验证
    if (dictFormRef.value) {
      dictFormRef.value.clearValidate()
    }

    try {
      // 获取字典详情
      const res = await SetupService.dictGetById({ dictId: row.dictId })
      if (res.code === ApiStatus.success) {
        const dictInfo = res.data || {}
        // 填充表单数据
        Object.assign(dictForm, {
          dictId: dictInfo.dictId,
          dictName: dictInfo.dictName,
          dictDescribe: dictInfo.dictDescribe,
          dictPid: dictInfo.dictPid || 0
        })

        // 如果是子级字典，获取父级名称
        if (dictInfo.dictPid && dictInfo.dictPid !== 0) {
          const parentDict = parentDictData.value.find(
            (item: DictType) => item.dictId === dictInfo.dictPid
          )
          if (parentDict) {
            parentDictName.value = parentDict.dictName || ''
          }
        }

        dictDialogVisible.value = true
      } else {
        ElMessage.error(res.message || '获取字典详情失败')
      }
    } catch (error) {
      ElMessage.error('获取字典详情失败')
      console.error(error)
    }
  }

  // 删除字典
  const handleDeleteDict = async (id: string | number) => {
    try {
      // 安全转换字段名称以匹配Ceres的API要求
      const dictId = safelyConvertToNumber(id)
      if (dictId === null) {
        ElMessage.error('无效的字典ID')
        return
      }

      // 检查删除的是否是当前选中的父级字典
      const isDeletingCurrentParent = currentParentKey.value === dictId

      const res = await SetupService.dictDelete({ dictId })
      if (res.code === ApiStatus.success) {
        ElMessage.success('删除成功')
        // 刷新父级字典列表
        await getParentDicts()

        // 优化逻辑：如果删除的是当前选中的父级字典
        if (isDeletingCurrentParent) {
          // 清空当前选中的父级字典
          currentParentKey.value = null
          parentDictName.value = ''
          // 清空子级表格数据
          childTableData.value = []
          childTotal.value = 0
        } else {
          // 如果删除的是其他字典，只刷新子级列表
          safelyGetChildDicts(currentParentKey.value)
        }
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }

  // 提交字典表单
  const handleDictSubmit = async () => {
    if (!dictFormRef.value) return

    try {
      await dictFormRef.value.validate()
      submitLoading.value = true

      // 构建提交数据，安全处理数字类型转换
      let formData: DictType

      if (isEdit.value) {
        // 编辑模式下构建formData
        formData = {
          dictName: dictForm.dictName,
          dictDescribe: dictForm.dictDescribe,
          dictId: safelyConvertToNumber(dictForm.dictId),
          dictPid: safelyConvertToNumber(dictForm.dictPid) || null
        } as DictType
      } else {
        // 新增模式下构建formData
        formData = {
          dictName: dictForm.dictName,
          dictDescribe: dictForm.dictDescribe,
          dictPid: safelyConvertToNumber(dictForm.dictPid) || null
        } as DictType

        // 如果有dictId且是编辑模式，则添加dictId
        const dictId = safelyConvertToNumber(dictForm.dictId)
        if (dictId !== null) {
          ;(formData as DictType & { dictId: number }).dictId = dictId
        }
      }

      let res
      if (isEdit.value) {
        // 编辑字典
        res = await SetupService.dictUpdate(formData)
      } else {
        // 新增字典
        res = await SetupService.dictAdd(formData)
      }

      if (res.code === ApiStatus.success) {
        ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
        dictDialogVisible.value = false
        // 刷新父级字典列表
        await getParentDicts()
        // 如果是子级字典操作，刷新子级列表
        safelyGetChildDicts(currentParentKey.value)
      } else {
        ElMessage.error(res.message || '操作失败')
      }
    } catch (error) {
      // 表单验证失败不处理，其他错误处理
      if (error instanceof Error) {
        ElMessage.error(isEdit.value ? '编辑失败' : '新增失败')
        console.error(error)
      }
    } finally {
      submitLoading.value = false
    }
  }

  // 字典对话框关闭时
  const onDictDialogClosed = () => {
    if (dictFormRef.value) {
      dictFormRef.value.clearValidate()
    }
    isAddingChild.value = false
  }
</script>

<style lang="scss" scoped>
  .setup-dict-container {
    padding: 20px;

    .search-form {
      padding: 15px;
      margin-bottom: 20px;
      background-color: var(--art-gray-50);
      border-radius: 4px;
    }

    .dict-layout {
      display: flex;
      gap: 20px;
      height: calc(100vh - 200px);
    }

    .parent-dict-panel {
      display: flex;
      flex: 1;
      flex-direction: column;
      border: 1px solid var(--art-border-color-light);
      border-radius: 4px;
    }

    .child-dict-panel {
      display: flex;
      flex: 1;
      flex-direction: column;
      border: 1px solid var(--art-border-color-light);
      border-radius: 4px;
    }

    .panel-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px 15px;
      font-weight: 500;
      background-color: var(--art-gray-50);
      border-bottom: 1px solid var(--art-border-color-light);
    }

    .parent-dict-table {
      flex: 1;
      padding: 10px;
      overflow-y: auto;
    }

    .child-dict-table {
      flex: 1;
      padding: 10px;
      overflow-y: auto;
    }

    .table-actions {
      display: flex;
      gap: 10px;
    }

    .dialog-footer {
      display: flex;
      gap: 10px;
      justify-content: flex-end;
    }
  }

  // 响应式设计 - IPad Pro
  @media screen and (max-width: $device-ipad-pro) {
    .setup-dict-container {
      .dict-layout {
        height: calc(100vh - 220px);
      }
    }
  }

  // 响应式设计 - IPad 竖屏
  @media screen and (max-width: $device-ipad-vertical) {
    .setup-dict-container {
      padding: 15px;

      .search-form {
        .el-form {
          .el-form-item {
            margin-right: 10px;
          }

          .el-input {
            width: 180px !important;
          }
        }
      }
    }
  }

  // 响应式设计 - IPad
  @media screen and (max-width: $device-ipad) {
    .setup-dict-container {
      padding: 15px;

      .dict-layout {
        flex-direction: column;
        height: auto;
        min-height: calc(100vh - 220px);
      }

      .parent-dict-panel,
      .child-dict-panel {
        height: 45vh;
        margin-bottom: 15px;
      }

      .el-dialog {
        width: 80% !important;
        max-width: 500px;
      }
    }
  }

  // 响应式设计 - 手机
  @media screen and (max-width: $device-phone) {
    .setup-dict-container {
      padding: 10px;

      .search-form {
        padding: 10px;
        margin-bottom: 15px;

        .el-form {
          .el-form-item {
            width: 100%;
            margin-right: 0;
            margin-bottom: 10px;
          }

          .el-input {
            width: 100% !important;
          }

          .el-button {
            margin-bottom: 5px;
          }
        }
      }

      .parent-dict-panel,
      .child-dict-panel {
        height: 40vh;
      }

      .panel-title {
        padding: 8px 10px;
        font-size: 14px;
      }

      // 表格容器包装器
      .parent-dict-table-wrapper,
      .child-dict-table-wrapper {
        display: flex;
        flex-direction: column;
        height: 100%;
        box-sizing: border-box;
      }
      
      // 表格内容区域
      .parent-dict-table,
      .child-dict-table {
        flex: 1;
        padding: 0;
        margin: 0;
        box-sizing: border-box;
        overflow-y: auto !important;
        overflow-x: hidden !important;
        touch-action: pan-y !important;
        -webkit-overflow-scrolling: touch !important;
      
        // 为整个表格容器添加样式
        :deep(.art-table-wrapper) {
          width: 100%;
          margin: 0;
          padding: 0;
          box-sizing: border-box;
        }
      }
      
      // 分页组件容器 - 父级字典
      .parent-pagination-wrapper,
      .child-pagination-wrapper {
        padding: 10px 0;
        box-sizing: border-box;
        overflow-x: auto !important;
        overflow-y: hidden !important;
        -webkit-overflow-scrolling: touch !important;
        overscroll-behavior: contain !important;
        touch-action: pan-x !important;
        border-top: 1px solid #ebeef5;
        display: flex;
        justify-content: flex-start;
      }
      
      // 为分页组件添加样式
      .parent-pagination-wrapper :deep(.el-pagination),
      .child-pagination-wrapper :deep(.el-pagination) {
        width: auto !important;
        display: flex !important;
        flex-wrap: nowrap !important;
        align-items: center !important;
        justify-content: flex-start !important;
        margin: 0 !important;
        padding: 0 10px !important;
      }
      
      // 确保分页组件的所有元素完全显示
      .parent-pagination-wrapper :deep(.el-pagination__sizes),
      .parent-pagination-wrapper :deep(.el-pagination__total),
      .child-pagination-wrapper :deep(.el-pagination__sizes),
      .child-pagination-wrapper :deep(.el-pagination__total) {
        margin-right: 10px !important;
        margin-left: 0 !important;
        white-space: nowrap !important;
        flex-shrink: 0 !important;
      }
      
      // 调整分页按钮间距
      .parent-pagination-wrapper :deep(.el-pagination__prev),
      .parent-pagination-wrapper :deep(.el-pagination__next),
      .parent-pagination-wrapper :deep(.el-pagination__number),
      .child-pagination-wrapper :deep(.el-pagination__prev),
      .child-pagination-wrapper :deep(.el-pagination__next),
      .child-pagination-wrapper :deep(.el-pagination__number) {
        margin: 0 2px !important;
        padding: 0 8px !important;
      }

      .table-actions {
        gap: 5px;
      }

      .el-table {
        font-size: 12px;
      }

      .el-dialog {
        width: 90% !important;
        max-width: 400px;
        margin: 10vh auto !important;
      }
    }
  }
</style>
